package com.book.shelves.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.book.breakage.entity.Accident;
import com.book.breakage.entity.Normal;
import com.book.breakage.service.AccidentService;
import com.book.breakage.service.BackService;
import com.book.breakage.service.NormalService;
import com.book.business.entity.BookSell;
import com.book.business.service.BookSellService;
import com.book.common.utils.WareBook;
import com.book.shelves.entity.BookStore;
import com.book.shelves.service.BookStoreService;
import com.book.common.annotation.ControllerEndpoint;
import com.book.common.annotation.Log;
import com.book.common.controller.BaseController;
import com.book.common.entity.FebsConstant;
import com.book.common.entity.FebsResponse;
import com.book.common.entity.QueryRequest;
import com.book.common.utils.FebsUtil;
import com.book.stat.entity.BreakageStat;
import com.book.stat.service.BreakageStatService;
import com.book.common.utils.BookMethod;
import com.book.warehouse.controller.WarehouseBookController;
import com.book.warehouse.entity.WarehouseBook;
import com.book.warehouse.entity.WarehouseHouseBook;
import com.book.warehouse.service.WarehouseBookService;
import com.book.warehouse.service.WarehouseHouseBookService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class BookStoreController extends BaseController {
    @Autowired
    BookStoreService bookStoreService;
    @Autowired
    BookSellService bookSellService;
    @Autowired
    NormalService normalService;
    @Autowired
    BackService backService;
    @Autowired
    BreakageStatService breakageStatService;
    @Autowired
    AccidentService accidentService;
    @Autowired
    WarehouseBookService warehouseBookService;
    @Autowired
    WarehouseHouseBookService warehouseHouseBookService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "shelves/bookStore")
    public String bookStoreIndex() {
        return FebsUtil.view("shelves/store/bookStoreList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "shelves/sold")
    public String bookWarnIndex() {
        return FebsUtil.view("shelves/store/bookStoreWarnList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "shelves/bookStore/add")
    public String bookStoreAdd() {
        return FebsUtil.view("shelves/store/bookStoreAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "shelves/bookStore/update/{id}")
    public String bookStoreUpdate(@PathVariable Integer id, ModelMap modelMap) {
        BookStore bookStore = this.bookStoreService.getById(id);
        modelMap.put("bookStore", bookStore);
        return FebsUtil.view("shelves/store/bookStoreUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "shelves/bookStore/plus/{id}")
    public String bookStorePlus(@PathVariable Integer id, ModelMap modelMap) {
        BookStore bookStore = this.bookStoreService.getById(id);
        modelMap.put("bookStore", bookStore);
        return FebsUtil.view("shelves/store/bookStorePlus");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "shelves/bookStore/minus/{id}")
    public String bookStoreMinus(@PathVariable Integer id, ModelMap modelMap) {
        BookStore bookStore = this.bookStoreService.getById(id);
        modelMap.put("bookStore", bookStore);
        return FebsUtil.view("shelves/store/bookStoreMinus");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "shelves/bookStore/ask/{id}")
    public String bookStoreAsk(@PathVariable Integer id, ModelMap modelMap) {
        BookStore bookStore = this.bookStoreService.getById(id);
        modelMap.put("bookStore", bookStore);
        return FebsUtil.view("shelves/store/bookStoreAsk");
    }

    @GetMapping("bookStore")
    @ResponseBody
    @RequiresPermissions("bookStore:view")
    public FebsResponse bookStoreList(BookStore bookStore) {
        return new FebsResponse().success().data(this.bookStoreService.findBookStore(bookStore));
    }

    @Log("访问架存窗口")
    @GetMapping("bookStore/list")
    @ResponseBody
    @RequiresPermissions("bookStore:view")
    public FebsResponse bookStoreIPage(QueryRequest request, BookStore bookStore) {
        Map<String, Object> dataTable = getDataTable(this.bookStoreService.pageBookStore(request, bookStore));
        return new FebsResponse().success().data(dataTable);
    }

    @Log("架存-预警")
    @PostMapping("bookStore/update")
    @ResponseBody
    @RequiresPermissions("bookStore:update")
    @ControllerEndpoint(operation = "修改书籍预警信息成功", exceptionMessage = "修改书籍预警信息失败")
    public FebsResponse bookStoreUpdate(BookStore bookStore) {
        BookStore store = bookStoreService.getById(bookStore.getId());
        if ("1".equals(store.getFlag())) {
            return new FebsResponse().message("该书籍正在申请报损！");
        }
        store.setWarningnumber(bookStore.getWarningnumber());
        if (store.getNum() < bookStore.getWarningnumber()) {
            store.setFlag("2");
        }
        if (store.getNum() >= bookStore.getWarningnumber()) {
            store.setFlag("0");
        }
        bookStoreService.updateBookStore(store);
        return new FebsResponse().success();
    }

    @Log("架存-下架")
    @PostMapping("bookStore/sold/{ids}")
    @ResponseBody
    @RequiresPermissions("bookStore:sold")
    @ControllerEndpoint(operation = "书籍下架成功", exceptionMessage = "书籍下架失败")
    public FebsResponse bookStorePlus(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<BookStore> bookStores = (List<BookStore>) bookStoreService.listByIds(Arrays.asList(attr));
        for (int i = 0; i < bookStores.size(); i++) {
            if ("1".equals(bookStores.get(i).getFlag())) {
                return new FebsResponse().message("报损中的书籍不能进行下架！");
            }
            warehouseBookService.update(new UpdateWrapper<WarehouseBook>().lambda()
                    .eq(WarehouseBook::getBookname, bookStores.get(i).getBookname())
                    .eq(WarehouseBook::getPutaway, "1")
                    .set(true, WarehouseBook::getPutaway, "0"));
            bookSellService.remove(new QueryWrapper<BookSell>().eq("bookname", bookStores.get(i).getBookname()));
        }
        bookStoreService.deleteBookStore(attr);
        return new FebsResponse().success();
    }

    @Log("架存-报损")
    @PostMapping("bookStore/minus")
    @ResponseBody
    @RequiresPermissions("bookStore:minus")
    @ControllerEndpoint(operation = "书籍报损申请成功", exceptionMessage = "书籍报损申请失败")
    public FebsResponse bookStoreMinus(BookStore bookStore) {
        String breId = BookMethod.getUUID();
        if ("1".equals(bookStore.getFlag())) {
            return new FebsResponse().message("该书籍已经申请报损，请耐心等候！");
        }
        BookStore store = bookStoreService.getById(bookStore.getId());
        if (store.getNum() < bookStore.getNum()) {
            return new FebsResponse().message("仓库共有" + store.getNum() + "本" + store.getBookname() + "，请核对报损数量！");
        }
        if (store.getNum() - bookStore.getNum() >= store.getWarningnumber()) {
            store.setFlag("0");
        }
        if (store.getNum() - bookStore.getNum() < store.getWarningnumber()) {
            store.setFlag("2");
        }
        Normal normalServiceOne = normalService.getOne(new QueryWrapper<Normal>().lambda().eq(Normal::getBookname, store.getBookname()).eq(Normal::getStatus, "0"));
        if (normalServiceOne != null && "1".equals(bookStore.getBookfrom())) {
            return new FebsResponse().message("该书籍已经在正常报损中。");
        }
        Accident accidentServiceOne = accidentService.getOne(new QueryWrapper<Accident>().lambda().eq(Accident::getBookname, store.getBookname()).eq(Accident::getStatus, "0"));
        if (accidentServiceOne != null && "3".equals(bookStore.getBookfrom())) {
            return new FebsResponse().message("该书籍已经在意外报损中。");
        }
        if ("1".equals(bookStore.getBookfrom())) {
            Normal normal = new Normal()
                    .setUsername(getCurrentUser().getUsername())
                    .setBreakageid(breId)
                    .setMessage(bookStore.getMessage())
                    .setPubid(bookStore.getPubid())
                    .setBookname(bookStore.getBookname())
                    .setBookmoney(bookStore.getBookmoney())
                    .setBooktype(bookStore.getType())
                    .setNumber(bookStore.getNum())
                    .setPrincipal(bookStore.getPrincipal())
                    .setBreakagedate(new Date())
                    .setTotalmoney(bookStore.getNum() * bookStore.getBookmoney())
                    .setStatus("0");
            normalService.normalAdd(normal);
        }
        if ("3".equals(bookStore.getBookfrom())) {
            Accident accident = new Accident()
                    .setBreakageid(breId)
                    .setUsername(getCurrentUser().getUsername())
                    .setMessage(bookStore.getMessage())
                    .setPubid(bookStore.getPubid())
                    .setBookname(bookStore.getBookname())
                    .setBookmoney(bookStore.getBookmoney())
                    .setBooktype(bookStore.getType())
                    .setNumber(bookStore.getNum())
                    .setPrincipal(bookStore.getPrincipal())
                    .setDamagedate(new Date())
                    .setTotalmoney(bookStore.getNum() * bookStore.getBookmoney())
                    .setStatus("0");
            accidentService.accidentAdd(accident);
        }
        // 添加报损统计信息
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        String yearAndMonths = format.format(calendar.getTime());
        String[] yearAndMonth = yearAndMonths.split("-");
        BreakageStat breakageStat = new BreakageStat()
                .setBookfrom(bookStore.getBookfrom())
                .setBookname(bookStore.getBookname())
                .setBooktype(bookStore.getType())
                .setPubid(bookStore.getPubid())
                .setBookmoney(bookStore.getBookmoney())
                .setNumber(bookStore.getNum())
                .setYear(yearAndMonth[0])
                .setMonth(yearAndMonth[1])
                .setOmit("0")
                .setTotalmoney(bookStore.getNum() * bookStore.getBookmoney())
                .setBreakageid(breId);
        breakageStatService.addCount(breakageStat);
        //将申请报损的书籍信息，添加
        bookStore.setFlag("1");
        //报损驳回时，确定数据用
        bookStore.setStoreid(store.getId());
        bookStore.setBreakageid(breId);
        bookStoreService.updateBookStore(store);
        BookStore bookStoreServiceOne = bookStoreService.getOne(new QueryWrapper<BookStore>().lambda().eq(BookStore::getBookname, store.getBookname()).eq(BookStore::getFlag, "1"));
        if (bookStoreServiceOne == null) {
            bookStoreService.addBookStore(bookStore);
        } else {
            bookStoreServiceOne.setNum(bookStoreServiceOne.getNum() + bookStore.getNum());
            bookStoreService.updateBookStore(bookStoreServiceOne);
        }
        //修改仓库
        WarehouseBook warehouseBook = warehouseBookService.getOne(new QueryWrapper<WarehouseBook>().lambda()
                .eq(WarehouseBook::getBookname, bookStore.getBookname())
                .eq(WarehouseBook::getPutaway, "1"));
        WareBook.wareBookChange(warehouseBook.getBookname(), "减少", bookStore.getNum());
        return new FebsResponse().success();
    }

    @Log("架存-下架")
    @PostMapping("bookStore/delete/{ids}")
    @ResponseBody
    @RequiresPermissions("bookStore:delete")
    @ControllerEndpoint(operation = "书籍下架成功", exceptionMessage = "书籍下架失败")
    public FebsResponse bookStoredelete(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<BookStore> bookStoreList = bookStoreService.askBookStore(attr);
        for (int i = 0; i < bookStoreList.size(); i++) {
            if ("1".equals(bookStoreList.get(i).getFlag())) {
                return new FebsResponse().message("正在申请报废的书籍不能进行下架！");
            }
            if ("2".equals(bookStoreList.get(i).getFlag())) {
                return new FebsResponse().message("请到预警管理界面，安排下架！");
            }
            this.bookStoreService.deleteBookStore(attr);
        }
        return new FebsResponse().success();
    }
}

